<template>
  <!-- 页面整体容器：包含查询区域、列表区域以及弹窗 -->
  <div class="role-management-page">
    <!-- 查询条件卡片 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryForm" label-width="80px" class="filter-form" inline>
        <el-form-item label="角色名称">
          <el-input
            v-model="queryForm.keyword"
            placeholder="支持模糊搜索角色名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表卡片：顶部工具条 + 固定高度表格 + 分页 -->
    <el-card class="list-card" shadow="never">
      <div class="table-toolbar">
        <div class="table-title">角色列表</div>
        <el-button type="primary" @click="openCreateDialog">新增角色</el-button>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :height="tableHeight"
          v-loading="loading"
          :empty-text="loading ? '加载中...' : '暂无数据'"
        >
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="rolename" label="角色名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="code" label="角色编码" min-width="150" show-overflow-tooltip />
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button type="primary" text size="small" @click="openEditDialog(scope.row)">
                编辑
              </el-button>
              <el-button type="warning" text size="small" @click="openPermissionDialog(scope.row)">
                权限配置
              </el-button>
              <el-button type="danger" text size="small" @click="confirmDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="pagination.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增 / 编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="520px" destroy-on-close>
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formModel.rolename" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formModel.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formModel.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formModel.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限配置弹窗 -->
    <el-dialog title="权限配置" v-model="permissionDialogVisible" width="600px" destroy-on-close>
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTreeData"
        :props="{ children: 'children', label: 'name' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermissionIds"
        :default-expand-all="true"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="permissionSubmitLoading" @click="submitPermission">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import myaxios from '@/Http/http'

interface RoleRecord {
  roleid: number | string | null
  rolename: string
  code: string
  description: string
  status: number
  createTime?: string
}
interface PermissionNode {
  id: number | string
  name: string
  code?: string
  children?: PermissionNode[]
}

const tableHeight = 420

// ===================== 页面状态 =====================
const loading = ref(false)
const submitLoading = ref(false)
const permissionSubmitLoading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const tableData = ref<RoleRecord[]>([])
const permissionTreeData = ref<PermissionNode[]>([])
const checkedPermissionIds = ref<(number | string)[]>([])
const currentRoleId = ref<number | string | null>(null)
const permissionTreeRef = ref()

// ===================== 查询表单 + 分页 =====================
const queryForm = reactive({
  keyword: '',
})

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

type RoleForm = RoleRecord
const defaultFormState = (): RoleForm => ({
  roleid: null,
  rolename: '',
  code: '',
  description: '',
  status: 1,
})

const formModel = reactive<RoleForm>(defaultFormState())
const formRef = ref<FormInstance>()

const formRules = reactive<FormRules<RoleForm>>({
  rolename: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  description: [{ required: false, message: '请输入角色描述', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
})

const dialogTitle = computed(() => (dialogMode.value === 'create' ? '新增角色' : '编辑角色'))

// ===================== 数据格式化工具 =====================
const normalizeListResponse = (payload: any) => {
  if (!payload) {
    return { items: [], total: 0 }
  }

  if (Array.isArray(payload)) {
    return { items: payload, total: payload.length }
  }

  if (Array.isArray(payload.listResult)) {
    return {
      items: payload.listResult,
      total: payload.totalcount ?? payload.listResult.length,
    }
  }

  if (Array.isArray(payload.items)) {
    return { items: payload.items, total: payload.total ?? payload.items.length }
  }

  if (Array.isArray(payload.result)) {
    return { items: payload.result, total: payload.totalcount ?? payload.result.length }
  }

  if (payload.data) {
    return normalizeListResponse(payload.data)
  }

  return { items: [], total: 0 }
}

// ===================== 列表数据 =====================
const fetchRoleList = async () => {
  loading.value = true
  try {
    const { data } = await myaxios.get('/api/Users/GetRoles', {
      params: {
        PageIndex: pagination.pageIndex,
        PageSize: pagination.pageSize,
        Rolename: queryForm.keyword,
      },
    })

    const normalized = normalizeListResponse(data?.result ?? data)
    tableData.value = normalized.items as RoleRecord[]
    pagination.total = normalized.total ?? 0
  } catch (error) {
    console.error('获取角色列表失败', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageIndex = 1
  fetchRoleList()
}

const handleReset = () => {
  queryForm.keyword = ''
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchRoleList()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchRoleList()
}

// ===================== 弹窗交互 =====================
const resetFormModel = () => {
  Object.assign(formModel, defaultFormState())
  formRef.value?.clearValidate()
}

const openCreateDialog = () => {
  dialogMode.value = 'create'
  resetFormModel()
  dialogVisible.value = true
}

const openEditDialog = (row: RoleRecord) => {
  dialogMode.value = 'edit'
  resetFormModel()
  Object.assign(formModel, row)
  dialogVisible.value = true
}

// ===================== 权限配置 =====================
const fetchPermissionTree = async () => {
  try {
    const { data } = await myaxios.get('/api/Permission/GetPermissionTree')
    const normalized = data?.result ?? data?.data ?? data
    permissionTreeData.value = Array.isArray(normalized) ? normalized : normalized?.items ?? []
  } catch (error) {
    console.error('获取权限树失败', error)
    permissionTreeData.value = []
  }
}

const fetchRolePermissions = async (roleId: number | string) => {
  try {
    const { data } = await myaxios.get('/api/Role/GetRolePermissions', {
      params: { roleId },
    })
    const normalized = data?.result ?? data?.data ?? data
    const permissions = Array.isArray(normalized) ? normalized : normalized?.items ?? []
    checkedPermissionIds.value = permissions.map((p: any) => p.id || p.permissionId)
  } catch (error) {
    console.error('获取角色权限失败', error)
    checkedPermissionIds.value = []
  }
}

const openPermissionDialog = async (row: RoleRecord) => {
  if (!row.roleid) return
  currentRoleId.value = row.roleid
  await fetchPermissionTree()
  await fetchRolePermissions(row.roleid)
  permissionDialogVisible.value = true
}

const submitPermission = async () => {
  if (!currentRoleId.value || !permissionTreeRef.value) return

  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]

  permissionSubmitLoading.value = true
  try {
    const { data } = await myaxios.post('/api/Role/AssignPermissions', {
      roleId: currentRoleId.value,
      permissionIds: allCheckedKeys,
    })

    if (data?.code === 200 || data?.status === 200) {
      ElMessage.success('权限配置成功')
      permissionDialogVisible.value = false
    } else {
      ElMessage.error(data?.message ?? '权限配置失败')
    }
  } catch (error) {
    console.error('配置权限失败', error)
    ElMessage.error('配置权限失败，请稍后再试')
  } finally {
    permissionSubmitLoading.value = false
  }
}

// ===================== 新增 / 编辑 / 删除 =====================
const submitForm = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    const request =
      dialogMode.value === 'create'
        ? myaxios.post('/api/Role/CreateRole', formModel)
        : myaxios.put('/api/Role/UpdateRole', formModel)

    request
      .then((res) => {
        if (res.data?.code === 200 || res.status === 200) {
          ElMessage.success(dialogMode.value === 'create' ? '新增成功' : '更新成功')
          dialogVisible.value = false
          fetchRoleList()
        } else {
          ElMessage.error(res.data?.message ?? '操作失败')
        }
      })
      .catch((error) => {
        console.error('保存角色失败', error)
        ElMessage.error('保存失败，请稍后再试')
      })
      .finally(() => {
        submitLoading.value = false
      })
  })
}

const confirmDelete = (row: RoleRecord) => {
  if (!row?.roleid) return
  ElMessageBox.confirm(`确定要删除角色「${row.rolename}」吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
  })
    .then(async () => {
      try {
        await myaxios.delete('/api/Role/DeleteRole', { data: { id: row.roleid } })
        ElMessage.success('删除成功')
        if (tableData.value.length === 1 && pagination.pageIndex > 1) {
          pagination.pageIndex -= 1
        }
        fetchRoleList()
      } catch (error) {
        console.error('删除角色失败', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

// ===================== 生命周期 =====================
onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.role-management-page {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-card {
  border-radius: 8px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 24px;
}

.list-card {
  border-radius: 8px;
}

.list-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
